#include <string>
#include <chrono>
#include <thread>
#include <iostream>

#include <zmq.hpp>

// zmq的router-dealer模式，router 会接收到 两 frame 的消息 ，第一帧是 发送端的 标识。第二帧才是 真正的数据。
// 同时 router 回复的时候，也要 发送两 frame

int main() {
    using namespace std::chrono_literals;

    // initialize the zmq context with a single IO thread
    zmq::context_t context{1};

    // construct a REP (reply) socket and bind to interface
    zmq::socket_t internalSocket{context, zmq::socket_type::pair};
    internalSocket.bind("ipc://frontend.ipc");

    zmq::socket_t socket{context, zmq::socket_type::dealer};
    socket.connect("tcp://127.0.0.1:8989");

    zmq_pollitem_t items[] = {
            {internalSocket, 0, ZMQ_POLLIN, 0},
            {socket,         0, ZMQ_POLLIN, 0}
    };
    for (;;) {
        int rc = zmq::poll(items, 2, 1);

        if (rc == -1) {
            break;
        }
        if (items[0].revents & ZMQ_POLLIN) {
            zmq::message_t msg;
            internalSocket.recv(msg, zmq::recv_flags::none);
            std::cout << "recv" << msg.to_string() << std::endl;
            socket.send(msg, zmq::send_flags::dontwait);
            std::cout << "send" << std::endl;
        }
        if (items[1].revents & ZMQ_POLLIN) {
            zmq::message_t msg;
            socket.recv(msg, zmq::recv_flags::none);
            std::cout << "Received " << msg.to_string() << std::endl;
        }
    }
   return 0;
}